//
//  StoneAPIManager.m
//  StoneAPI
//
//  Created by 陈小东 on 15/3/14.
//  Copyright (c) 2015年 _____stone_chenxiaodong_____. All rights reserved.
//

#import "StoneAPIManager.h"
#import "UtilsMacro.h"
#import "StoneCache.h"
#import "StoneModel.h"
#import "NSString+DeviceId.h"

#pragma mark - 配置
#ifdef DEBUG
NSString * const APIServerHost = @"http://192.168.0.200/stone-rest/rest/stone/";
#else
NSString * const APIServerHost = @"http://192.168.0.200/stone-rest/rest/stone/";
#endif

#pragma mark - 错误定义
#define CACHE_KEY(cmd,parameters)[F(@"%@%@", cmd,parameters)MD5]
#pragma mark -

NSString * const UserCacheKey = @"/UserCacheKey";

@implementation StoneAPIManager

+ (instancetype)sharedManager{
    static StoneAPIManager *instance;
    instance = [self manager];
    instance.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    return instance;
}

+ (NSString *)fetchAPIServerUrl{
    return kFormat(@"%@", APIServerHost);
}

- (void)setCurrentUser:(User *)currentUser{
    _currentUser = currentUser;
    [NSKeyedArchiver archiveRootObject:currentUser toFile:[kDocumentsPath stringByAppendingString:UserCacheKey]];
}

- (User *)currentUser{
    if (!_currentUser) {
        _currentUser = [NSKeyedUnarchiver unarchiveObjectWithFile:[kDocumentsPath stringByAppendingString:UserCacheKey]];
    }
    return _currentUser;
}

- (BOOL)isLogined{
    return !!self.currentUser;
}
@end

#pragma mark - 内部私有相关

@implementation StoneAPIManager(Private)

- (NSString *)jsonStringWithDictionary:(NSDictionary *)dic{
    NSError * err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:0
                                                         error:&err];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    return jsonString;
}

- (id)jsonStringToJson:(NSString *)jsonString{
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return json;
}

- (AFHTTPRequestOperation *)customPostWithParameters:(id)parameters
                                             cmdName:(NSString *)cmdName
                                         resultClass:(Class)resultClass
                                             success:(SUCCESS_BLOCK)success
                                             failure:(FAIL_BLOCK)failure{
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
                                                                                URLString:kFormat(@"%@%@.json", APIServerHost,cmdName)
                                                                               parameters:parameters
                                                                constructingBodyWithBlock:nil
                                                                                    error:nil];
    request.timeoutInterval = 20;
    id successBlock = ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSInteger code = [responseObject[@"result"] intValue];
        if (code == 1100 || code == 1){
            if(responseObject && resultClass){
                StoneObject *obj = [[resultClass alloc] initWithDictionary:responseObject];
                if (success)
                    success(obj);
            }else{
                if (success)
                    success(responseObject);
            }
        }else{
            NSError * error = [[NSError alloc]initWithDomain:NSXMLParserErrorDomain
                                                        code:code
                                                    userInfo:@{NSLocalizedDescriptionKey:responseObject}];
            if (failure)
                failure(error);
        }
    };
    id failureBlock = ^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure)
            failure(error);
    };
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
                                                                      success:successBlock
                                                                      failure:failureBlock];
    [self.operationQueue addOperation:operation];
    return operation;
}

@end

@implementation StoneAPIManager(recommend)

- (void)actionRecommendSuccess:(SUCCESS_BLOCK)success
                       failure:(FAIL_BLOCK)failure{
    [self customPostWithParameters:@{}
                           cmdName:@"entrance"
                       resultClass:nil
                           success:success
                           failure:failure];
}
@end
